﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TyNetCoreBlog.Models.Data;
using TyNetCoreBlog.Models.Entities;
using TyNetCoreBlog.Repository.RepositoryBase;

namespace TyNetCoreBlog.Repository
{
    public class TagRepository : RepositoryBase<Tag, int>, ITagRepository
    {
        public TagRepository(AppDbContext dbContext):base(dbContext)
        {
        }


        /// <summary>
        /// 重写GetAllAsync
        /// </summary>
        /// <returns></returns>
        public override Task<IEnumerable<Tag>> GetAllAsync()
        {
            return Task.FromResult(DbContext.Set<Tag>().Include(x => x.BlogTags)
                .OrderByDescending(x => x.BlogTags.Count).AsEnumerable());
        }

        /// <summary>
        /// 重写GetByIdAsync
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public override Task<Tag> GetByIdAsync(int id)
        {
            return DbContext.Set<Tag>().Include(x => x.BlogTags)
                .Where(x => x.Id == id).FirstOrDefaultAsync();
        }

        
        /// <summary>
        /// 判断名称是否存在
        /// </summary>
        /// <param name="name"></param>
        /// <returns>存在返回true，否则返回false</returns>
        public bool NameIsExits(string name)
        {
            var cate = DbContext.Set<Tag>().Where(x => x.Name == name).FirstOrDefault();
            return cate != null;
        }
    }
}
